<template>
  <div class="image-list">
      <div class="change">
        <el-radio-group v-model="collect" size="mini" @change="onCollect">
          <el-radio-button label="false">全部</el-radio-button>
          <el-radio-button label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button size="mini" type="success" @click="dialogClose=true" v-if="isShowAddBtn">上传素材</el-button>
      </div>
      <el-row :gutter="20">
        <el-col  :lg="4" :md="6" :xs="12" :sm="6" v-for="(item,index) in imagesList" :key="index" class="col-box" @click.native="cur=index">
          <el-image
              style="height:100%;width:100%;"
              :src="item.url"
              fit="cover">
          </el-image>
          <div class="cur" v-if="isShowCur && cur===index"></div>
          <div class="icon-desc" v-if="isShowAction">
                <el-button
                type="warning"
                :icon="item.is_collected ? 'el-icon-star-on':'el-icon-star-off'"
                circle size="mini"
                 @click="onCollectIcon(item)"
                :loading="item.loading"
                 ></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" :loading="item.loading" circle @click="onDelete(item)"></el-button>
          </div>
        </el-col>
      </el-row>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        @current-change="onPageChange"
        :current-page.sync="currentPage"
        >
      </el-pagination>
       <!-- 上传素材-->
      <el-dialog title="上传素材" :visible.sync="dialogClose" :append-to-body="true" width="395px">
          <!--
            upload组件本身就支持请求提交上传操作
            请求方法：默认POST
            请求路径：必须是完整路径
              on-success用不了？？？
          -->

          <el-upload
            v-if="dialogClose"
            :show-file-list="false"
            class="upload-demo"
            drag
            action="http://api-toutiao-web.itheima.net/mp/v1_0/user/images"
            :headers="uploadHeader"
            name="image"
            multiple
            :before-upload="onUploadSuccese"
            >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
      </el-dialog>
  </div>
</template>

<script>
import { getImage, getCollect, imgDelete } from '@/api/image.js'
export default {
  name: 'imageIndex',
  components: {},
  props: {
    // 添加素材按钮
    isShowAddBtn: {
      type: Boolean,
      default: true
    },
    // 收藏和删除是否显示
    isShowAction: {
      type: Boolean,
      default: true
    },
    // 是否展示选择
    isShowCur: {
      type: Boolean,
      default: false
    }
  },
  data () {
    const user = JSON.parse(window.localStorage.getItem('user'))
    return {
      collect: false, // 默认查询全部素材列表
      imagesList: [],
      dialogClose: false,
      uploadHeader: {
        Authorization: `Bearer ${user.token}`
      },
      total: 0,
      pageSize: 20, // 每页大小
      currentPage: 1, // 当前页码
      cur: null
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadImage()
  },
  mounted () {},
  methods: {
    loadImage (page = 1) {
      // 重置高亮页码，防止数据和页码不对应
      this.currentPage = page
      this.cur = null

      getImage({
        collect: this.collect,
        page: page,
        per_page: this.pageSize
      }).then(res => {
        const { results } = res.data.data
        results.forEach(img => {
          // img对象没有loading数据，我们这里手动往里面添加该数据，用来控制每个收藏按钮的loading状态
          img.loading = false
        })
        this.imagesList = results
        this.total = res.data.data.total_count
      })
    },
    onCollect () {
      this.loadImage()
    },
    onUploadSuccese () {
      console.log('上传成功~')

      this.loadImage(this.currentPage)
      this.dialogClose = false
    },
    onPageChange (page) {
      this.loadImage(page)
    },
    onCollectIcon (collectData) {
      collectData.loading = true
      getCollect(collectData.id, !collectData.is_collected).then((res) => {
        // console.log(res)
        collectData.is_collected = !collectData.is_collected
        collectData.loading = false
      })
    },
    onDelete (data) {
      data.loading = true
      imgDelete(data.id).then(res => {
        // 删除成功
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.loadImage(this.page)
        data.loading = false
      })
    }
  }
}
</script>

<style scoped lang="less">
.change{
  padding-bottom: 20px;
  display: flex;
  justify-content: space-between;
}
.col-box{
  position: relative;
  margin:10px;
  height:140px;
  padding: 0!important;
  cursor: pointer;
}
.icon-desc{
  height:30px;
  position: absolute;
  bottom: 0;
  left:0;
  right:0;
  background: rgba(0,0,0,0.5);
  font-size:25px;
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  color:#fff;
}
.cur{
  background: url(./images/selected.png) no-repeat ;
  background-size: cover;
  width:100px;
  height: 100px;
  position: absolute;
  left:0;
  top:0;
  right:0;
  bottom:0;
  margin:auto;
}
</style>
